<template>
  <el-dialog
    :title="title ? title: $t('jspImageCropperDialog.title')"
    :visible.sync="dialogVisible"
    :lock-scroll="true"
    :modal="modal"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :destroy-on-close="true"
    :width="width"
    :before-close="handleBeforeClose"
    custom-class="vueCropper-dialog"
    @close="handleClose"
    @open="handleOpen"
  >
    <div class="vueCropper-content">
      <div class="vueCropper-left">
        <vueCropper
          ref="cropper"
          :img="option.img"
          :output-size="option.size"
          :output-type="option.outputType"
          :info="option.info"
          :can-scale="option.canScale"
          :auto-crop="option.autoCrop"
          :auto-crop-width="option.autoCropWidth"
          :auto-crop-height="option.autoCropHeight"
          :fixed="option.fixed"
          :fixed-number="option.fixedNumber"
          :full="option.full"
          :fixed-box="option.fixedBox"
          :can-move="option.canMove"
          :can-move-box="option.canMoveBox"
          :original="option.c"
          :center-box="option.centerBox"
          :high="option.high"
          :info-true="option.infoTrue"
          :max-img-size="option.maxImgSize"
          :enlarge="option.enlarge"
          :mode="option.mode"
          @realTime="handleRealTime"
          @imgMoving="handleImgMoving"
          @cropMoving="handleCropMoving"
          @imgLoad="handleImgLoad"
        />
        <div class="button-group">
          <el-button type="primary" :disabled="submitLoading" @click="handleRefreshCrop">{{ $t('jspImageCropperDialog.refresh') }}</el-button>
          <el-button type="primary" :disabled="submitLoading" @click="handleChangeScale(1)">{{ $t('jspImageCropperDialog.roomIn') }}</el-button>
          <el-button type="primary" :disabled="submitLoading" @click="handleChangeScale(-1)">{{ $t('jspImageCropperDialog.roomOut') }}</el-button>
          <el-button type="primary" :disabled="submitLoading" @click="handleRotateLeft">{{ $t('jspImageCropperDialog.rotateLeft') }}</el-button>
          <el-button type="primary" :disabled="submitLoading" @click="handleRotateRight">{{ $t('jspImageCropperDialog.rotateRight') }}</el-button>
        </div>
      </div>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="handleCancel">{{ $t('common.cancel') }}</el-button>
      <el-button type="primary" :loading="submitLoading" @click="HandleConfirm">{{ $t('common.confirm') }}</el-button>
    </div>
  </el-dialog>

</template>

<script>
import { VueCropper } from 'vue-cropper'
export default {
  name: 'JspImageCropperDialog',
  components: {
    VueCropper
  },
  props: {
    title: {
      type: String,
      default: ''
    },
    // 显示对话框
    visible: {
      type: Boolean,
      default: false
    },
    // 对话框宽度
    width: {
      type: String,
      default: '60%'
    },
    // 选项配置
    cropperConfig: {
      type: Object,
      default: () => {
        return {}
      }
    },
    // 源文件信息
    originFile: {
      type: Object,
      default: () => {
        return {}
      }
    },
    // 是否上传前置，表示将进行上传操作，通过this.$emit(this.isUpload ? 'upload' ...交由父组件进行上传
    isUpload: {
      type: Boolean,
      default: false
    },
    // 是否遮罩
    modal: {
      type: Boolean,
      default: true
    }
  },
  data() {
    const defaultOption = {
      img: '',	// 裁剪图片的地址：url地址、base64、blob
      outputSize: 1,	// 裁剪生成图片的质量：0.1 ~ 1
      outputType: 'png',	// 裁剪生成图片的格式：jpeg、png、webp
      info: true,	// 裁剪框的大小信息：true、false
      canScale: true, //	图片是否允许滚轮缩放：true、false
      autoCrop: true,	// 是否默认生成截图框：true、false
      autoCropWidth: 300,	// 默认生成截图框宽度：	0 ~ max
      autoCropHeight: 300,	// 默认生成截图框高度：	0 ~ max
      fixed: true,	// 是否开启截图框宽高固定比例：true、false
      fixedNumber: [1, 1],	// 截图框的宽高比例：[ 宽度 , 高度 ]
      full: false,	// 是否输出原图比例的截图：true、false
      fixedBox: false,	// 固定截图框大小：true、false
      canMove: true,	// 上传图片是否可以移动：true、false
      canMoveBox: true,	// 截图框能否拖动：true、false
      original: false,	// 上传图片按照原始比例渲染：true、false
      centerBox: true,	// 截图框是否被限制在图片里面：true、false
      high: false,	// 是否按照设备的dpr 输出等比例图片：true、false
      infoTrue: true,	// true 为展示真实输出图片宽高： false、true
      maxImgSize: 3000,	// 限制图片最大宽度和高度：0 ~ max
      enlarge: 1, // 图片根据截图框输出比例倍数：0 ~ max(建议不要太大不然会卡死的呢)
      mode: 'contain'// 图片默认渲染方式：contain、cover、100px、100% auto
    }
    for (var i in defaultOption) {
      for (var option in this.cropperConfig) {
        if (i === option) {
          defaultOption[i] = this.cropperConfig[option]
        }
      }
    }

    return {
      previews: {},
      previewStyle1: {},
      dialogVisible: this.visible,
      option: defaultOption,
      priview_active_name: 'first',
      submitLoading: false
    }
  },
  watch: {
    // 监听value变化
    visible(value) {
      this.dialogVisible = value
    },
    cropperConfig(value) {
      for (var i in this.option) {
        for (var j in value) {
          if (i === j) {
            this.option[i] = value[j]
          }
        }
      }
    },
    isUpload(value) {
      this.submitLoading = value
    }
  },
  mounted() {
  },
  methods: {
    // 实时预览事件
    handleRealTime(data) {
      this.previews = data
      this.$emit('realTime', data)
    },
    // 图片移动回调函数
    handleImgMoving(data) {
      this.$emit('imgMoving', data)
    },
    // 截图框移动回调函数
    handleCropMoving(data) {
      this.$emit('cropMoving', data)
    },
    // 图片加载的回调
    handleImgLoad(data) {
      this.$emit('imgMoving', data)
    },
    handleRefreshCrop() {
      this.$refs.cropper.refresh()
    },
    handleChangeScale(number) {
      this.$refs.cropper.changeScale(number || 1)
    },
    handleRotateLeft() {
      this.$refs.cropper.rotateLeft()
    },
    handleRotateRight() {
      this.$refs.cropper.rotateRight()
    },
    async handleBeforeClose(done) {
      if (this.submitLoading) {
        const response = await this.$confirm(this.$t('jspImageCropperDialog.close_confirm_tips'), {
          confirmButtonText: this.$t('common.confirm'),
          cancelButtonText: this.$t('common.cancel'),
          type: 'warning'
        }).catch(() => {})
        if (response !== 'confirm') return false
      }
      done()
    },
    handleClose() {
      this.submitLoading = false
      this.dialogVisible = false
      this.$emit('close')
    },
    async handleCancel() {
      if (this.submitLoading) {
        const response = await this.$confirm(this.$t('jspImageCropperDialog.cancel_confirm_tips'), {
          confirmButtonText: this.$t('common.confirm'),
          cancelButtonText: this.$t('common.cancel'),
          type: 'warning'
        }).catch(() => {})
        if (response !== 'confirm') {
          return false
        }
      }
      this.submitLoading = false
      this.dialogVisible = false
      this.$emit('close')
    },
    handleOpen() {
    },
    // 确认裁剪/上传操作
    HandleConfirm() {
      this.submitLoading = this.isUpload
      this.$refs.cropper.getCropBlob((blob) => {
        const returnData = { blob, base64: URL.createObjectURL(blob), origin: this.originFile }
        this.$emit(this.isUpload ? 'upload' : 'cut', returnData)
      })
    }

  }
}
</script>
<style  lang="scss"  scoped>
@import '~@/styles/variables.scss';
::v-deep .vueCropper-dialog {
  .el-dialog__header {
     border-bottom: 1px solid #{$border-color-base};
  }
  .el-dialog__body {
    padding: 0 20px;
    .vueCropper-content {
      .vueCropper-left {
        display: flex;
        margin:30px 20px 30px 0;
        flex-direction: column;
        height:450px;
        .vue-cropper {
          flex: 9;
        }
        .button-group {
          padding-top: 10px;
          flex: 1;
          > * {
            margin:0 10px 10px 0!important
          }
        }
      }
    }
  }

  .el-dialog__footer {
    border-top: 1px solid #{$border-color-base};
  }
}

</style>
